<?php
declare (strict_types=1);

namespace app\api\controller\v2;

use app\common\model\ApiMember;
use app\common\model\Cate;
use app\common\model\Question as QuestionModel;
use app\common\model\QuestionCol;
use app\common\model\QuestionPinglun;
use app\common\model\QuestionZan;
use think\facade\Db;

class Question extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        return sucessMsg('200', '获取成功', [
            'cate' => $this->cate(),//获取问答分类
        ]);
    }

    /**
     *获取问答分类
     */
    public function cate()
    {
        return Cate::where(['type' => 3, 'status' => 1])
            ->field('id,name')
            ->order('sort', 'asc')
            ->select();
    }

    /**
     *获取问答列表
     */
    public function wenda()
    {
        $page = input('page/d', 1);
        $cate_id = input('id/d');
        $model = new QuestionModel();
        $listRows = 7;
        $where['status'] = 1;
        if (!empty($cate_id)) $where['cate_id'] = $cate_id;
        $wenda = $model->where($where)
            ->field('id,picture,title,content,zan_num,comment_num,col_num,created_at')
            ->order('sort', 'asc')
            ->page($page, $listRows)
            ->withAttr('picture', function ($val, $data) {
                return env('app.yuming') . $val;
            })
            ->select();
        $count = $model->where($where)->count();
        $maxpage = ceil($count / $listRows);
        return sucessMsg('200', '获取成功', ['wenda' => $wenda, 'page' => $page, 'maxpage' => $maxpage]);
    }

    /**
     *获取问答详情
     */
    public function details()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(422, '无id查询');
        }
        $details = QuestionModel::where(['status' => 1, 'id' => $id])
            ->field('id,title,name,label,content,image,zan_num,comment_num,col_num,created_at')
            ->find();
        if (empty($details)) {
            return errMsg(422, '页面丢失，请稍后再试！');
        }
        $details['image'] = env('app.yuming') . $details['image'];
        $details['created_at'] = date('Y-m-d H:i:s');
        //判断是否点赞
        $is_zan = QuestionZan::where(['status' => 1, 'question_id' => $id, 'zan_member_id' => $this->user_id])->count();
        $details['is_zan'] = 0;
        if ($is_zan > 0) $details['is_zan'] = 1;
        //判断是否收藏
        $is_col = QuestionCol::where(['status' => 1, 'question_id' => $id, 'col_member_id' => $this->user_id])->count();
        $details['is_col'] = 0;
        if ($is_col > 0) $details['is_col'] = 1;
        return sucessMsg('200', '获取成功', ['details' => $details]);
    }

    public function zan()
    {
        $question_id = input('id/d', 1);
        $is_zan = input('is_zan/d', 0);
        $model = New QuestionModel();
        $question_zanModel = New QuestionZan();
        $data = [];
        $data['zan_member_id'] = $this->user_id;
        $data['member_id'] = $model->where(['status' => 1, 'id' => $question_id])
            ->value('member_id');
        $data['question_id'] = $question_id;
        if ($is_zan == 0) {
            //开启事务
            Db::startTrans();
            try {
                $data['is_zan'] = 1;
                $question_zanModel->save($data);
                $model->where('id', $question_id)
                    ->inc('zan_num', 1)
                    ->update();
                Db::commit();
                return sucessMsg('200', '点赞成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('400', '系统繁忙，请稍后再试');
            }
        } else {
            //开启事务
            Db::startTrans();
            try {
                $question_zanModel->where(['zan_member_id' => $data['zan_member_id'],
                    'member_id' => $data['member_id'],
                    'question_id' => $data['question_id']
                ])->delete();
                $model->where('id', $question_id)
                    ->dec('zan_num', 1)
                    ->update();
                Db::commit();
                return sucessMsg('200', '取消点赞成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('400', '系统繁忙，请稍后再试');
            }
        }
    }

    public function col()
    {
        $question_id = input('id/d', 1);
        $is_col = input('is_col/d', 0);
        $model = New QuestionModel();
        $question_colModel = New QuestionCol();
        $data = [];
        $data['col_member_id'] = $this->user_id;
        $data['member_id'] = $model->where(['status' => 1, 'id' => $question_id])
            ->value('member_id');
        $data['question_id'] = $question_id;
        if ($is_col == 0) {
            //开启事务
            Db::startTrans();
            try {
                $data['is_col'] = 1;
                $question_colModel->save($data);
                $model->where('id', $question_id)
                    ->inc('col_num', 1)
                    ->update();
                Db::commit();
                return sucessMsg('200', '收藏成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('400', '系统繁忙，请稍后再试');
            }
        } else {
            //开启事务
            Db::startTrans();
            try {
                $question_colModel->where(['col_member_id' => $data['col_member_id'],
                    'member_id' => $data['member_id'],
                    'question_id' => $data['question_id']
                ])->delete();
                $model->where('id', $question_id)
                    ->dec('col_num', 1)
                    ->update();
                Db::commit();
                return sucessMsg('200', '取消收藏成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('400', '系统繁忙，请稍后再试');
            }
        }
    }

    //显示评论
    public function list()
    {
        $id = input('question_id/d');
        if (empty($id)) {
            return '无id查询';
        }
        //查询出用户名头像和评论内容
        $data = QuestionPinglun::where(['question_id' => $id, 'is_pinglun' => 1])
            ->with('getmember')
            ->field('content,member_id,created_at')
            ->order('id desc')
            ->select();
        foreach ($data as &$v) {
            $v['image'] = $v->getmember->image;
            $v['image'] = env('app.yuming') . $v['image'];
            $v['member_id'] = $v->getmember->account;
            $v['created_at'] = date('Y-m-d H:i:s', strtotime($v['created_at']));
            unset($v->getmember);
        }
        return sucessMsg('200', '获取成功！', ['data' => $data]);
    }

    //发表评论
    public function pinglun()
    {
        $id = input('question_id/d');
        if (empty($id)) {
            return '无id查询';
        }
        $data = input('post.');
        $data['is_pinglun'] = input('is_zan/d', 0);
        $data['member_id'] = $this->user_id;
        $data['question_id'] = $id;
        if (empty($data['content'])) {
            return "请输入评论内容";
        }
        $content = $data['content'];
        $model = new QuestionPinglun();
        $model1 = new QuestionModel();
        if ($data['is_pinglun'] == 0) {
            //开启事务
            Db::startTrans();
            try {
                $model1->where('id', $id)
                    ->inc('comment_num', 1)
                    ->update();
                $data['is_pinglun'] = 1;
                $model->save($data);
                $model2 = new ApiMember();
                $data = $model2->where('id', $data['member_id'])->field('id,account,image')->select();
                foreach ($data as &$v) {
                    $v['image'] = env('app.yuming') . $v['image'];
                }
                Db::commit();
                return sucessMsg('200', '评论成功', [
                    'personal' => $data,
                    'content' => $content
                ]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
        }
    }
}
